/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/* eslint-disable react/sort-comp */
/* eslint-disable react/jsx-no-bind */
/* eslint-disable react/no-unused-state */
import React, { Component, useCallback, useState, useMemo, useEffect } from 'react';
import { connect } from 'dva';
import { List, Input, Card, Row, Col, Button, Modal, message, Popconfirm, Table } from 'antd';
import IconFont from '@/components/IconFont';
import qs from 'qs';
import { isLegalData } from '@/utils/utils';
import router from 'umi/router';
import { getYzStatus } from '@/services/api';
import SelectPQModal from '@/components/_pages/Post/Area/SelectPQModal';
import ModifyZYModal from './ModifyZYModal';
import styles from './index.less';

const { TextArea } = Input;

// 关闭原因输入组件
const CloseReason = props => {
  const [reason, updateReason] = useState('');
  const handleChange = useCallback(e => {
    const { value } = e.target;
    updateReason(value);
    props.onChange(value);
  }, []);
  return (
    <TextArea
      placeholder="请输入内容"
      style={{ height: 100 }}
      maxLength={500}
      value={reason}
      onChange={handleChange}
    />
  );
};
CloseReason.defaultProps = {
  onChange() {},
};

const authMap = {
  '-1': '入库',
  7: '驿站代收',
  12: '派件+驿站代收',
  13: '到派+驿站代收',
};

const BrandManagement = ({ children, style, className, cm_id, title }) => {
  const [visible, setVisible] = useState(false);
  const [dataSource, setDataSource] = useState([]);
  const columns = useMemo(
    () => [
      {
        dataIndex: 'brand',
        key: 'brand',
        title: '品牌',
        align: 'center',
      },
      {
        dataIndex: 'auth',
        key: 'auth',
        title: '开通功能',
        align: 'center',
        render: auth => authMap[auth],
      },
    ],
    [],
  );

  useEffect(
    () => {
      visible &&
        cm_id &&
        getYzStatus({ cm_id }).then(res => {
          const { code, msg, data } = res;
          if (code == 0) {
            setDataSource(isLegalData(data));
          } else {
            message.error(msg);
          }
        });
    },
    [cm_id, visible],
  );

  const onClick = useCallback(() => {
    setVisible(true);
  }, []);

  const onCancel = useCallback(() => {
    setVisible(false);
  }, []);

  return (
    <>
      <Button style={style} className={className} onClick={onClick}>
        {children}
      </Button>
      <Modal width={608} centered onCancel={onCancel} visible={visible} title={title} footer={null}>
        <Table rowKey="brand" columns={columns} dataSource={dataSource} pagination={false} />
      </Modal>
    </>
  );
};

@connect(({ area, loading, user, setting }) => ({
  area,
  user,
  zySubPostStationsLoading: loading.effects['area/zyGetSubPostStations'],
  zyAuditLoading: loading.effects['area/zyGetSubPostStationsToBeChecked'],
  closeing: loading.effects['area/CloseAreaPost'],
  deleteing: loading.effects['area/deleteArea'],
  approved: loading.effects['area/approved'],
  submitting: loading.effects['area/applyCloseDak'],
  noPwdLogin: loading.effects['area/noPwdLogin'],
  ...setting,
}))
export default class AreaList extends Component {
  constructor(props) {
    super(props);
    this.state = {
      downVisible: false,
      deleteVisible: false,
      auditVisible: false,
      cm_id: null,
      downType: false,
      imgVisible: false,
      zyVisible: false,
      record: {},
      pqVisible: false,
    };
  }

  // 记录当前关闭原因
  handleChangeReason = (value = '') => {
    this.reason = value;
  };

  // 申请关闭
  onDownClick = cm_id => {
    this.setState({
      downVisible: true,
      cm_id,
    });
    this.handleChangeReason();
    Modal.confirm({
      title: '您确认申请关闭该驿站？',
      content: (
        <div>
          <p>
            该关闭申请将由快宝驿站工作人员进行审核，如果关闭申请通过，该驿站将无法在登录使用快宝驿站产品，包含快宝驿站APP、快宝驿站网页版等。
          </p>
          <p>您也可以直接与快宝驿站工作人员联系关闭事宜。</p>
          <p>联系电话：13818443483；QQ：2881505377</p>
          <p>关闭原因：</p>
          <CloseReason onChange={this.handleChangeReason} />
        </div>
      ),
      centered: true,
      okText: '确认',
      cancelText: '取消',
      onOk: () => this.onOkDownClick(cm_id),
    });
  };

  // 申请关闭确认
  onOkDownClick = cm_id =>
    new Promise((resolve, reject) => {
      const { dispatch } = this.props;
      if (!this.reason) {
        const errMsg = '请输入关闭原因';
        message.error(errMsg);
        reject(errMsg);
      } else {
        dispatch({
          type: 'area/applyCloseDak',
          payload: {
            cm_id,
            reason: this.reason,
          },
          then: code => {
            if (code == 0) {
              this.setState({
                downVisible: false,
                downType: true,
              });
            }
            resolve();
          },
        });
      }
    });

  // 审核申请通过
  auditClick = (cm_id, post) => {
    this.setState({
      auditVisible: true,
      cm_id,
    });
    Modal.confirm({
      title: '温馨提示',
      content:
        post == 6 ? '是否将该驿站移入‘区域内独立驿站’？' : '审核通过后该驿站将能使用出入库功能。',
      centered: true,
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        this.onOkAudit(cm_id);
      },
    });
  };

  // 申请通过确定
  onOkAudit = cm_id => {
    const { dispatch, post } = this.props;
    dispatch({
      type: 'area/approved',
      payload: {
        cm_id,
        is_pass: 1,
        post,
      },
    });
    this.setState({
      auditVisible: false,
    });
  };

  // 从下属驿站中删除
  onDeleteClick = cm_id => {
    this.setState({
      deleteVisible: true,
      cm_id,
    });
    Modal.confirm({
      title: '温馨提示',
      content: '您确定把该驿站从下属驿站中删除？',
      centered: true,
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        this.onOkDelete(cm_id);
      },
    });
  };

  // 从下属驿站中删除确定
  onOkDelete = cm_id => {
    const { dispatch } = this.props;
    dispatch({
      type: 'area/deleteArea',
      payload: {
        cm_id,
      },
    });
    this.setState({
      deleteVisible: false,
    });
  };

  // 免密登录
  adminClick = cm_id => {
    const {
      dispatch,
      options: { key },
    } = this.props;
    const isZyAccount = key === 'post';
    dispatch({
      type: 'area/noPwdLogin',
      payload: {
        cm_id,
      },
      then: code => {
        if (code == 0) {
          let yzHost = '';
          let url = '';
          if (isZyAccount) {
            yzHost = '//yz.chinapostcnps.com';
            url = '/api/Authorization/chinaPostNoPwdLogin';
          } else {
            yzHost = '//yz.kuaidihelp.com';
            url = '/api/Authorization/noPwdLogin';
          }
          const redirect = `${url}?${qs.stringify({ dak_id: cm_id })}`;
          const openUrl = `${yzHost}?agent=${encodeURIComponent(redirect)}&nonceKey=dak_id`;
          window.open(openUrl);
        }
      },
    });
  };

  // 图片链接
  imgModel = item => {
    this.setState({
      imgVisible: true,
      imgUrl: item,
    });
  };

  // 查看详情
  checkDetail = cm_id => {
    router.push({
      pathname: '/post/area/postDetail',
      query: {
        cm_id,
      },
    });
  };

  // 中邮禁用或恢复驿站
  zyForbidOrRecover(cm_id, status) {
    const { dispatch, getList } = this.props;
    dispatch({
      type: 'area/zyForbidOrRecover',
      payload: {
        cm_id,
        status,
      },
    }).then(() => {
      getList && getList();
    });
  }

  /**
   * 拒绝通过审核
   *  */
  rejectInn = ({ cm_id, status, to_branch_id }) => {
    const {
      dispatch,
      // getList,
      getAreaRefusList,
      options: { key },
    } = this.props;
    const isZyAccount = key === 'post';
    const type = isZyAccount ? 'area/zyAudit' : 'area/rejectInn';
    const payload = isZyAccount
      ? {
          cm_id,
          status,
          to_branch_id,
        }
      : {
          cm_id,
          is_pass: 2,
        };

    dispatch({
      type,
      payload,
    }).then(() => {
      // 刷新拒绝驿站列表
      getAreaRefusList && getAreaRefusList();
    });
  };

  // 中邮，修改所属支局
  handleModifyZJ(record, path) {
    this.showModal(true);
    this.setState({
      record: {
        path,
        ...record,
      },
    });
  }

  // 控制支局弹窗
  showModal(bool) {
    this.setState({
      zyVisible: bool,
    });
  }

  // 跳转数据统计
  jumpTo(cm_id) {
    const { dispatch } = this.props;
    dispatch({
      type: 'global/changeTabActiveKey',
      payload: {
        list: 'overview',
      },
    });
    router.push({
      pathname: '/post/list',
      query: {
        cm_id,
      },
    });
  }

  showPQModal = data => {
    this.setState({
      pqVisible: true,
      record: data,
    });
  };

  renderTitleBtn = ({
    post,
    userKey,
    area_ids,
    item,
    isZyAccount,
    zyForbidden,
    isZJ,
    openYzPq,
  }) => {
    const isYz = userKey === 'yz';
    // 公司层级片区管理
    const notCompanyArea = userKey == 'yz' && area_ids !== '*';

    // 下属驿站
    if (post == '1') {
      return (
        <>
          <Button
            className={styles.btn_admin}
            onClick={() => {
              this.adminClick(item.cm_id);
            }}
          >
            登录该驿站网页版
          </Button>
          {isYz &&
            openYzPq && (
              <Button
                className={styles.btn_admin}
                style={{ float: 'right' }}
                onClick={this.showPQModal.bind(this, item)}
              >
                片区分配
              </Button>
            )}
          <Button
            className={styles.btn_admin}
            style={{ float: 'right' }}
            onClick={this.jumpTo.bind(this, item.cm_id)}
          >
            数据统计
          </Button>
          {!isZyAccount ? (
            !notCompanyArea ? (
              <Button
                className={styles.btn_admin}
                style={{ float: 'right' }}
                onClick={() => {
                  this.onDeleteClick(item.cm_id);
                }}
              >
                从下属驿站中移除
              </Button>
            ) : (
              ''
            )
          ) : (
            // 下属驿站
            <div style={{ float: 'right' }}>
              {zyForbidden ? (
                <Popconfirm
                  key="rec"
                  title="确定恢复该账号？"
                  onConfirm={this.zyForbidOrRecover.bind(this, item.cm_id, 1)}
                >
                  <Button className={styles.btn_admin}>恢复使用</Button>
                </Popconfirm>
              ) : (
                <>
                  <Button
                    className={styles.btn_admin}
                    style={{ float: 'right' }}
                    onClick={() => {
                      this.checkDetail(item.cm_id);
                    }}
                  >
                    查看详情
                  </Button>
                  {!isZJ && (
                    <Button
                      className={styles.btn_admin}
                      onClick={this.handleModifyZJ.bind(this, item, 'under_modify')}
                    >
                      修改所属支局
                    </Button>
                  )}
                  <Popconfirm
                    key="forbid"
                    title="确定禁用该账号？"
                    onConfirm={this.zyForbidOrRecover.bind(this, item.cm_id, 2)}
                  >
                    <Button className={styles.btn_admin}>禁用账号</Button>
                  </Popconfirm>
                </>
              )}
            </div>
          )}
          {!zyForbidden && (
            <BrandManagement
              className={styles.btn_admin}
              style={{ float: 'right' }}
              cm_id={item.cm_id}
              title={item.inn_name}
            >
              品牌管理
            </BrandManagement>
          )}
        </>
      );
    }

    if (post == '2') {
      return (
        <div>
          {item.apply_status == '0' ? (
            <Button disabled>申请中</Button>
          ) : (
            <Button
              className={styles.btn_admin}
              onClick={() => {
                this.onDownClick(item.cm_id);
              }}
              style={{ cursor: 'pointer', float: 'right' }}
            >
              申请关闭
            </Button>
          )}
        </div>
      );
    }

    if (post == '3') {
      return (
        <div>
          <Popconfirm
            disabled={item.rejected || item.passed}
            title={isZyAccount ? '确定拒绝审核通过该驿站？' : '是否将该驿站移入‘已拒绝驿站’？'}
            onConfirm={this.rejectInn.bind(this, {
              cm_id: item.cm_id,
              status: 2,
            })}
          >
            <Button disabled={item.rejected || item.passed} className={styles.btn_admin}>
              {item.rejected ? '已拒绝' : '拒绝'}
            </Button>
          </Popconfirm>
          <Button
            disabled={item.passed || item.rejected}
            className={styles.btn_admin}
            onClick={() => {
              isZyAccount ? this.handleModifyZJ(item, 'audit') : this.auditClick(item.cm_id, post);
            }}
          >
            {item.passed ? '已审核通过' : '审核通过'}
          </Button>
        </div>
      );
    }

    if (post == '6') {
      return (
        <div>
          <Button
            disabled={item.passed || item.rejected}
            className={styles.btn_admin}
            onClick={() => {
              isZyAccount ? this.handleModifyZJ(item, 'audit') : this.auditClick(item.cm_id, post);
            }}
          >
            {item.passed ? '已审核通过' : '审核通过'}
          </Button>
        </div>
      );
    }

    return null;
  };

  render() {
    const { imgVisible, imgUrl, zyVisible, record, pqVisible } = this.state;
    const {
      data: { list, paginations },
      loading,
      closeing = false,
      deleteing = false,
      approved = false,
      noPwdLogin = false,
      post, // 1:下属驿站，2:区域内独立驿站，3:待审核驿站，4:驿站加盟申请, 6: 已拒绝驿站
      user: {
        currentUser: { user_info = {} },
      },
      zyForbidden,
      zySubPostStationsLoading,
      zyAuditLoading,
      getList = () => {}, // 获取当前页面列表数据
      options: { key: userKey },
    } = this.props;
    const { branchLevel, area_ids, inn_area_ids = [] } = user_info;
    // 判断是否是中邮用户
    const isZyAccount = userKey === 'post';
    // 判断是否是支局账号，支局不显示“修改所属支局”按钮
    const isZJ = branchLevel == '4';
    // 公司层级账号开启驿站片区管理功能，则显示‘分配片区’按钮，片区账号全部隐藏
    const openYzPq = area_ids == '*' && inn_area_ids.length > 0;
    const { page = 1, pageSize = 20 } = paginations || {};
    return (
      <div className={styles.main}>
        <List
          loading={
            loading ||
            closeing ||
            deleteing ||
            noPwdLogin ||
            approved ||
            zySubPostStationsLoading ||
            zyAuditLoading
          }
          itemLayout="horizontal"
          dataSource={list}
          renderItem={(item, key) => (
            <Card style={{ marginBottom: '25px' }}>
              <List.Item>
                <List.Item.Meta
                  title={
                    post == '4' ? (
                      ''
                    ) : (
                      <div className={styles.information_title}>
                        <span className={styles.ft_tow}>
                          <i>{key + 1 + (page - 1) * pageSize}</i>
                          {item.inn_name}
                        </span>
                        {this.renderTitleBtn({
                          post,
                          userKey,
                          area_ids,
                          item,
                          isZyAccount,
                          zyForbidden,
                          isZJ,
                          openYzPq,
                        })}
                      </div>
                    )
                  }
                  description={
                    <div className={styles.information}>
                      {post == '4' ? (
                        <div>
                          <Row className={styles.mb_20}>
                            <Col>
                              <span className={styles.bag_bor}>
                                <IconFont type="phone" />
                              </span>
                              {item.name}
                              <span className={styles.ml_r_20}>|</span>
                              <span>
                                电话：
                                {item.phone}
                              </span>
                              <span className={styles.ml_r_20}>|</span>
                              <span>
                                创建时间：
                                {item.create_time}
                              </span>
                            </Col>
                          </Row>
                          <Row className={styles.mt_b_20}>
                            <Col>
                              <span className={styles.bag_bor_area}>
                                <IconFont type="address" />
                              </span>
                              {item.location}
                              <span className={styles.ml_r_20}>|</span>
                              {item.province}
                              {item.city}
                              {item.district}
                              {item.town || ''}
                              {item.address}
                            </Col>
                          </Row>
                          <Row>
                            <Col>
                              <div>
                                <span className={styles.bag_bor_time}>
                                  <IconFont type="qita" />
                                </span>
                                <span>快递品牌：</span>
                                {item.brand}
                                <span className={styles.ml_r_20}>|</span>
                                <span>票数：</span>
                                {item.delivery_num}
                                {item.picture_path ? (
                                  <div style={{ display: 'inline-block' }}>
                                    <span className={styles.ml_r_20}>|</span>
                                    {item.picture_path.map(items => (
                                      <a
                                        style={{ marginRight: '10px' }}
                                        onClick={() => this.imgModel(items)}
                                      >
                                        图片链接
                                      </a>
                                    ))}
                                  </div>
                                ) : (
                                  ''
                                )}
                              </div>
                            </Col>
                          </Row>
                        </div>
                      ) : (
                        <div>
                          {post == 1 &&
                            !zyForbidden && (
                              <Row className={styles.mt_b_20}>
                                <Col>
                                  <span className={styles.bag_bor_storage}>
                                    <IconFont type="icon-test" />
                                  </span>
                                  <span>
                                    昨日入库：
                                    {item.yesterday_in_num}
                                    ，较前日：
                                    {item.in_growth_num}
                                  </span>
                                  {!isZyAccount && (
                                    <>
                                      <span className={styles.ml_r_20}>|</span>
                                      <span>
                                        快宝指数：
                                        {item.score}
                                      </span>
                                    </>
                                  )}
                                </Col>
                              </Row>
                            )}
                          <Row className={styles.mt_b_20}>
                            <Col>
                              <span className={styles.bag_bor}>
                                <IconFont type="phone" />
                              </span>

                              {item.concat_name}
                              <span className={styles.ml_r_20}>|</span>
                              <span>
                                手机号码：
                                {item.phone}
                              </span>
                              <span className={styles.ml_r_20}>|</span>
                              <span>
                                联系手机号码：
                                {item.concat_phone}
                              </span>
                              {item.area_name && (
                                <>
                                  <span className={styles.ml_r_20}>|</span>
                                  <span>
                                    片区：
                                    {item.area_name}
                                  </span>
                                </>
                              )}
                            </Col>
                          </Row>
                          <Row className={styles.mt_b_20}>
                            <Col>
                              <span className={styles.bag_bor_area}>
                                <IconFont type="address" />
                              </span>
                              {post == '3' && isZyAccount ? (
                                ''
                              ) : (
                                <>
                                  {item.area ||
                                    isLegalData(item.branch, [])
                                      .filter(val => val.level > 0)
                                      .map(val => val.name)
                                      .join(' ')}
                                  <span className={styles.ml_r_20}>|</span>
                                </>
                              )}
                              {item.province}
                              {item.city}
                              {item.district}
                              {item.town || ''}
                              {item.address || item.concat_location}
                            </Col>
                          </Row>
                          <Row>
                            <Col>
                              <div>
                                <span className={styles.bag_bor_time}>
                                  <IconFont type="time" />
                                </span>
                                <span>注册时间：</span>
                                {item.create_at}
                                {post == '1' ? (
                                  <div className={styles.join}>
                                    <span className={styles.ml_r_20}>|</span>
                                    {zyForbidden ? (
                                      <span>
                                        禁用时间：
                                        {item.disabled_at}
                                      </span>
                                    ) : (
                                      <span>
                                        加盟时间：
                                        {item.join_time || item.join_at}
                                      </span>
                                    )}
                                  </div>
                                ) : post == '6' ? (
                                  <div className={styles.join}>
                                    <span className={styles.ml_r_20}>|</span>
                                    <span>审核时间：</span>
                                    {item.update_at}
                                  </div>
                                ) : (
                                  ''
                                )}
                              </div>
                            </Col>
                          </Row>
                        </div>
                      )}
                      {post == '1' ? (
                        <div className={styles.qrcode}>
                          {item.qrcode ? (
                            <a
                              target="_blank"
                              rel="noreferrer"
                              href={`https://city.kuaidihelp.com/Api/YZ/CourierStation/downloadQrcode?file=${encodeURIComponent(
                                item.qrcode,
                              )}&name=${item.inn_name}`}
                            >
                              <img src={item.qrcode} alt="" title="" />
                            </a>
                          ) : (
                            ''
                          )}
                        </div>
                      ) : (
                        ''
                      )}
                    </div>
                  }
                />
              </List.Item>
            </Card>
          )}
        />
        <Modal
          title="上传资料"
          visible={imgVisible}
          onCancel={() => {
            this.setState({ imgVisible: false });
          }}
          footer={
            <Button
              key="submit"
              type="primary"
              onClick={() => {
                this.setState({ imgVisible: false });
              }}
            >
              确定
            </Button>
          }
        >
          <img src={imgUrl} alt="" style={{ width: '470px' }} />
        </Modal>
        <ModifyZYModal
          visible={zyVisible}
          record={record}
          showModal={this.showModal.bind(this)}
          getList={getList}
        />
        <SelectPQModal
          title="片区分配"
          visible={pqVisible}
          record={record}
          getList={getList}
          onCancel={() => {
            this.setState({
              pqVisible: false,
            });
          }}
        />
      </div>
    );
  }
}
